package com.example.musiccommunity.util;

import android.content.Context;
import android.util.Log;

import com.example.musiccommunity.bean.Song;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class MusicDataLoader {
    private static final String TAG = "MusicDataLoader";
    private static final String JSON_FILE = "songs.json";

    // 加载歌曲列表
    public static List<Song> loadSongs(Context context) {
        String jsonString = loadJSONFromAsset(context);
        if (jsonString == null) {
            return null;
        }

        Gson gson = new Gson();
        Type listType = new TypeToken<List<Song>>(){}.getType();
        return gson.fromJson(jsonString, listType);
    }

    // 从assets读取JSON文件
    private static String loadJSONFromAsset(Context context) {
        String json;
        try {
            InputStream is = context.getAssets().open(JSON_FILE);
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, StandardCharsets.UTF_8);
        } catch (IOException ex) {
            Log.e(TAG, "Error reading JSON file: " + ex.getMessage());
            return null;
        }
        return json;
    }

    // 获取raw音频资源ID
    public static int getRawResourceId(Context context, String rawResName) {
        return context.getResources().getIdentifier(rawResName, "raw", context.getPackageName());
    }

    // 获取drawable封面资源ID
    public static int getDrawableResourceId(Context context, String drawableResName) {
        return context.getResources().getIdentifier(drawableResName, "drawable", context.getPackageName());
    }
}